/* eslint-disable no-param-reassign */
import React, { useState, useRef } from 'react';
import { useRequest } from 'umi';
import { Button, Input, TreeSelect, Divider, message, Popconfirm, Tag } from 'antd';
import { PaginationProps } from 'antd/lib/pagination';
import arrToTree from 'array-to-tree';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';

import CreateForm from '@/components/CreateForm';
import { api } from '@/services/config';
import { getRoles, roles } from '../service';
import { RoleItem, PermissionItem, TreeNodeItem, SearchParam } from '../data';
import { getQuertParam, exportExcel } from '@/utils/utils';

const Role: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [pagination] = useState<PaginationProps>({});
  const [selectRecord, setSelectRecord] = useState<RoleItem | undefined>({});
  const [modalVisible, handleModalVisible] = useState<boolean>(false);
  const [searchParam, setSearchParams] = useState<SearchParam>({});
  const { data: menus } = useRequest(api.system.menus);

  const convertTreeData = (): TreeNodeItem[] => {
    const treeNodes: TreeNodeItem[] = [];
    menus.forEach((ele: PermissionItem) => {
      treeNodes.push({
        value: `${ele.id}`,
        label: `${ele.menuName}`,
        key: `${ele.id}`,
        parentId: ele.parentId,
      });
    });
    return treeNodes;
  };

  const handlePermissionList = (record: RoleItem | undefined) => {
    if (record?.permissionList && record?.permissionList.length > 0) {
      return record.permissionList.map((permission: PermissionItem) => ({
        value: permission.id + '', //字符串
        label: permission.menuName,
      }));
    }
    return undefined;
  };

  const columns: ProColumns<RoleItem>[] = [
    {
      title: '序号',
      width: 50,
      align: 'center',
      dataIndex: 'index',
      valueType: 'index',
      render: (text, record, index) => {
        const { current = 1, pageSize = 10 } = pagination;
        return (current - 1) * pageSize + index + 1;
      },
    },
    {
      title: '角色名称',
      width: 100,
      align: 'center',
      dataIndex: 'roleName',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入角色名称',
          },
        ],
      },
      renderFormItem: (item, { type, defaultRender, ...rest }) => {
        if (type === 'form') {
          return <Input {...rest} placeholder="请输入角色名称" />;
        }
        return defaultRender(item);
      },
    },
    {
      title: '角色描述',
      width: 100,
      align: 'center',
      dataIndex: 'description',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入角色描述',
          },
        ],
      },
      renderFormItem: (item, { type, defaultRender, ...rest }) => {
        if (type === 'form') {
          return <Input {...rest} placeholder="请输入角色名称" />;
        }
        return defaultRender(item);
      },
    },
    {
      title: '权限列表',
      width: 400,
      align: 'center',
      dataIndex: 'permissionList',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record: RoleItem) => {
        let menusArr = record.permissionList;
        if (menusArr && menusArr.length > 0) {
          return menusArr.map((item: PermissionItem) => <Tag color="blue">{item.menuName}</Tag>);
        } else {
          return '-';
        }
      },
      renderFormItem: (item, { type, defaultRender, ...rest }) => {
        if (type === 'form') {
          return (
            <TreeSelect
              // {...rest}
              placeholder="请为角色分配权限"
              allowClear
              showSearch
              style={{ width: '100%' }}
              dropdownStyle={{ overflow: 'auto' }}
              treeData={arrToTree(convertTreeData(), {
                parentProperty: 'parentId',
                customID: 'value',
              })}
              treeCheckable
              // 父节点可勾选
              treeCheckStrictly
            />
          );
        }
        return defaultRender(item);
      },
    },
    {
      title: '操作',
      width: 80,
      align: 'center',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              setSelectRecord(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title="确定删除该角色?"
            onConfirm={() => {
              roles({ method: 'delete', id: record.id }).then(({ code, msg }) => {
                if (code === 0) {
                  message.success('删除成功！');
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                } else {
                  message.error(msg);
                }
              });
            }}
            okText="是"
            cancelText="否"
            placement="left"
          >
            <a href="#">删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  /**
   * 导出
   * @param form
   */
  const handleExport = (form: any) => {
    const url =
      '/api/role/download?current=' +
      searchParam.current +
      '&pageSize=' +
      searchParam.pageSize +
      '&order=' +
      searchParam.order +
      '&sortParam=' +
      searchParam.sortParam +
      '&param=' +
      JSON.stringify(searchParam.param);

    // 导出
    exportExcel(url);
  };

  return (
    <PageContainer title={false}>
      <ProTable<RoleItem>
        rowKey="id"
        bordered
        columns={columns}
        actionRef={actionRef}
        pagination={{
          pageSize: 10,
        }}
        toolBarRender={false}
        request={(params) => {
          // return roles({ ...params });

          const { current, pageSize, ...data } = params;
          const paramsT = {
            current,
            pageSize,
            order: true,
            sortParam: 'id',
            param: getQuertParam(data),
          };
          //保存查询参数,导出使用
          setSearchParams(paramsT);
          return getRoles(paramsT); // 单独处理查询请求，因为里面含有特殊参数param,含大括号，自动转义
        }}
        postData={(data: any) => data.records || []}
        search={{
          optionRender: ({ searchText, resetText }, { form }) => [
            <Button
              key="search"
              type="primary"
              onClick={() => {
                form?.submit();
              }}
            >
              {searchText}
            </Button>,
            <Button
              type="primary"
              onClick={() => {
                handleModalVisible(true);
                setSelectRecord(undefined);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
            <Button
              key="rest"
              onClick={() => {
                form?.resetFields();
                form?.submit();
              }}
            >
              {resetText}
            </Button>,
            <Button key="out" onClick={() => handleExport(form)}>
              导出
            </Button>,
          ],
        }}
      />
      <CreateForm
        modalVisible={modalVisible}
        title={selectRecord ? '修改角色' : '新增角色'}
        onCancel={() => {
          handleModalVisible(false);
          setSelectRecord(undefined);
        }}
      >
        <ProTable<RoleItem, RoleItem>
          rowKey="id"
          type="form"
          columns={columns}
          form={{
            labelCol: { span: 5 },
            wrapperCol: { span: 19 },
            initialValues: {
              ...selectRecord,
              //必须放置在最下方，覆盖上面解构的结果
              permissionList: handlePermissionList(selectRecord),
            },
          }}
          onSubmit={async (value) => {
            let permissionList: { id: number }[] = [];
            if (value.permissionList) {
              permissionList = value.permissionList.map((x: any) => {
                return { id: Number.parseInt(x.value) };
              });
              delete value?.permissionList;
            }
            const values = {
              method: selectRecord ? 'PUT' : 'POST',
              ...selectRecord,
              ...value,
              permissionList,
            };
            const { code, msg } = await roles(values);
            if (code === 0) {
              handleModalVisible(false);
              message.success(selectRecord ? '修改角色成功' : '新建角色成功');
              if (actionRef.current) {
                actionRef.current.reload();
              }
            } else {
              message.error(msg);
            }
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default Role;
